#include <cstdio>
#include <iostream>
#include "HEpoll.h"
#include "AliasRef.h"

/**
 * 测试服务端功能
 */

#define CHKRET(r) if(r){printf("line:%d "  #r "=%d\n", __LINE__, r); return r;}

atomic_int g_recv_count(0);
atomic_ullong g_recv_bytes(0);

void OnRequest(const string& msg, weak_ptr<ConnectMeta> wconnMeta)
{
    //printf("recv Req: %s\n", msg.c_str());
    auto connMeta = wconnMeta.lock();
    //connMeta->sendMsg(msg);
    connMeta->sendMsg("R\n");
    //g_recv_count += 1;
    //g_recv_bytes += msg.size();
}

void SplitReqest(queue<string>& reqQueue, string& stream, weak_ptr<ConnectMeta>)
{
    g_recv_count += 1;
    g_recv_bytes += stream.size();
    reqQueue.push("R");
    printf("recv bytes: %llu count:%d\n", g_recv_bytes.load(), g_recv_count.load());
    stream.clear();
}

int main(int argc, char** argv)
{
    HEpoll hep;
    int ret = hep.init();
    CHKRET(ret);

    hep.setAliasNameInstance(make_shared<AliasRef<ConnectMetaSPtr>>());
    hep.run(true);


    auto lisnMeta = hep.addTcpListen(argc > 1? stoi(argv[1]) :8888);
    ret = lisnMeta->setKeepAlive(60);
    CHKRET(ret);
    lisnMeta->onMessageReachFunc = OnRequest;
    lisnMeta->splitReqFunc = SplitReqest;
    lisnMeta->start();

    ConnectMetaSPtr connMeta;
    string input;
    while (cin >> input, input != "q")
    {
        if ("r" == input)
        {
            g_recv_bytes = 0;
            g_recv_count = 0;
        }
        else if ('p' == input[0])
        {
            printf("hep status=%s\n", hep.toString().c_str());
            printf("recv=%llu bytes %d rows\n", g_recv_bytes.load(), g_recv_count.load());
            if (input[1] > 0)
            {
                int fd = stoi(input.c_str()+1);
                auto connMeta = hep.find(fd);
                if (connMeta)
                {
                    printf("fd=%d : %s\n", fd, connMeta->toString().c_str());
                }
            }
        }
        
        input.clear();
    }

    printf("notify Exit");
    hep.notifyExit();
    hep.unInit();
    return 0;
}